""" 需要使用到ADB命令的一系列操作 """

import shutil
import subprocess
import signal
import os
import re
from adb import fileparsers


def check_adb_path():
    """ 检查adb命令路径中是否存在 """
    return shutil.which('adb') is not None


def check_device_attached():
    output = subprocess.check_output(['adb', 'devices'])
    output = output.strip()
    last_line = output.splitlines()[-1]
    return b'List of devices' not in last_line and b'daemon started' not in last_line


def check_adb_forward():
    output = subprocess.check_output(['adb', 'forward', '--list'])
    output = output.strip()
    if len(output) == 0:
        return False
    last_line = output.splitlines()[-1]
    return b'daemon started' not in last_line and b'tcp' in last_line


def adb_forward():
    os.system('adb forward tcp:9318 tcp:9318')


def adb_filter(filter, buffer='events'):
    shell = subprocess.Popen(['adb', 'shell', 'logcat', '-b', buffer], stdout=subprocess.PIPE)
    try:
        while True:
            line = shell.stdout.readline()
            if line != b'':
                line = str(line, 'utf-8')
                items = re.split(r' +', line, 6)
                pid = items[2]
                tid = items[3]
                level = items[4]
                tag = items[5]
                content = items[6]
                if filter(pid, tid, tag, content):
                    fileparsers.log_highlight(level, line)
            else:
                print('捕捉到空')
    except KeyboardInterrupt:
        print('退出adb shell')
